package com.hyfd.deal.Flow;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.hyfd.common.GenerateData;
import com.hyfd.common.utils.DateUtils;
import com.hyfd.common.utils.MapUtils;
import com.hyfd.common.utils.ToolHttp;
import com.hyfd.common.utils.XmlUtils;
import com.hyfd.deal.BaseDeal;

public class WangXinFlowDeal implements BaseDeal {
	
	private static Logger log = Logger.getLogger(LeMianFlowDeal.class);

	@Override
	public Map<String, Object> deal(Map<String, Object> order) {
		Map<String, Object> map = new HashMap<String, Object>();
        int flag = -1;
        try
        {
        	// 1.获取订单参数
            String phoneNo = (String)order.get("phone");// 手机号
            String spec = new Double(order.get("value") + "").intValue() + "";// 流量包大小
           
            // 2.生成自家平台订单号
            String curids = "hb" + DateUtils.getNowTimeToMS() + phoneNo + GenerateData.getStrData(2);
            map.put("orderId", curids);
            
			// 3.获取物理通道信息
            Map<String, Object> channel = (Map<String, Object>)order.get("channel"); // 获取物理通道
            String defaultParameter = (String)channel.get("default_parameter");// 默认参数
            Map<String, String> paramMap = XmlUtils.readXmlToMap(defaultParameter.trim());
            String userName = paramMap.get("userName").toString();
            String key = paramMap.get("key").toString();	
            String orderTime = paramMap.get("orderTime").toString();	// 订购有效时间(月),固定值1
            String range = paramMap.get("range").toString();
            String linkUrl = paramMap.get("linkUrl").toString();
            String backurl = paramMap.get("callbackUrl").toString();
            String timeStamp = DateUtils.getNowDateTime().toString();
            
            // 4.计算充值签名
            String sign = paramSign(userName, phoneNo, spec, timeStamp, key);
            
            String paramData = paramFormat(userName, phoneNo, spec, orderTime, curids, range, sign, timeStamp, backurl);
            
            String result = ToolHttp.post(false, linkUrl, paramData, null);
            if (null == result) {
                String myMsg = "网信[流量充值]请求超时,手机号[" + phoneNo + "],流量包[" + spec + "MB]";
                log.error(myMsg);
            } else {
            	JSONObject jsonObj = JSONObject.parseObject(result);
            	String code = jsonObj.getString("code");
            	String msg = jsonObj.getString("msg");
            	String reqNo = jsonObj.getString("reqNo");
            	
                map.put("resultCode", code + ":" + msg);
                map.put("providerOrderId", reqNo);
            	
        		if ("0000".equals(code)) {
        			 flag = 1;
				} else {
					flag = 0;
					log.error("网信[流量充值]请求:提交失败,手机号["+phoneNo+"],流量包["+spec+"MB],原因["+msg+"]");
				}
            }
        } catch (ConnectTimeoutException | SocketTimeoutException e) {
        	// 请求、响应超时
            flag = -1;
        } catch (Exception e) {
            log.error("网信[流量充值]出错" + e.getMessage() + "||" + MapUtils.toString(order));
        }
        map.put("status", flag);
        
        return map;
	}
	
	/**
	 * @功能描述：	格式化请求参数
	 *
	 * @作者：zhangpj		@创建时间：2017年8月11日
	 * @param userName 用户名
	 * @param mobile 订购手机号码
	 * @param orderMeal 订购流量
	 * @param orderTime 订购时间 固定值1
	 * @param msgId 用户侧订单号
	 * @param range 流量类型
	 * @param notifyUrl 回调地址
	 * @return String json数据
	 */
	private String paramFormat(String userName,String mobile,String orderMeal,String orderTime,
			String msgId,String range,String sign,String timeStamp,String notifyUrl){
		Map<String, String> map = new LinkedHashMap<String, String>();
		map.put("userName", userName);
		map.put("mobile", mobile);
		map.put("orderMeal", orderMeal);
		map.put("orderTime", orderTime);
		map.put("msgId", msgId);
		map.put("range", range);
		map.put("sign", sign);
		map.put("timeStamp", timeStamp);
		map.put("notifyUrl", notifyUrl);

		return JSONObject.toJSONString(map);
	}
	
	/**
	 * @功能描述：	拼接加密字符串并返回计算好的签名
	 *
	 * @作者：zhangpj		@创建时间：2017年8月11日
	 * @param map
	 * @return
	 */
	private String paramSign(String userName,String mobile,String orderMeal,String timeStamp,String key){
		StringBuffer sbf = new StringBuffer();
		sbf.append("userName"+userName);
		sbf.append("mobile"+mobile);
		sbf.append("orderMeal"+orderMeal);
		sbf.append("timeStamp"+timeStamp);
		sbf.append("key"+key);
		
		return SHA1(sbf.toString());
	}
	
	/**
	 * @功能描述：	sha1 加密
	 *
	 * @作者：zhangpj		@创建时间：2017年8月10日
	 * @param decript
	 * @return
	 */
	private String SHA1(String decript) {
		System.out.println("被加密的明文[" + decript + "]");
		try {
			MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
			digest.update(decript.getBytes());
			byte messageDigest[] = digest.digest();
			// Create Hex String
			StringBuffer hexString = new StringBuffer();
			// 字节数组转换为 十六进制 数
			for (int i = 0; i < messageDigest.length; i++) {
				String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
				if (shaHex.length() < 2) {
					hexString.append(0);
				}
				hexString.append(shaHex);
			}
			return hexString.toString();

		} catch (Exception e) {
			e.printStackTrace();
			log.error("网信签名方法出错|"+e.getMessage());
		}
		return "";
	}
	
	public static void main(String[] args) {
		// 提交订单
//		subminOrder();
		System.out.println("-----------------------------------------");
		// 查询订单
//		queryOrder();
		
		String result = "{\"code\":\"0000\",\"msg\":\"订购成功\",\"reqNo\":\"P123456789123456789\"}";
		JSONObject jsonObj = JSONObject.parseObject(result);
		System.out.println(jsonObj.get("code"));
		System.out.println(jsonObj.get("msg"));
		System.out.println(jsonObj.get("reqNo"));
		
		
		
	}

	private static void subminOrder() {
		String linkUrl = "http://103.254.78.187:8082/apiFlow/order/singleNumber";
		String key = "54F896BF-3399-4BC7-BF2A-EF72F4107F13";
		String userName = "JNhaobaiBDP";
		String orderTime = "1";	// 订购有效时间(月),固定值1

		String mobile = "13280009366";
		String orderMeal = "20";
		String msgId = "hb"+DateUtils.getNowTimeToMS()+mobile+GenerateData.getStrData(2);
		String range = "1";
		String timeStamp = DateUtils.getNowDateTime().toString();
		String notifyUrl = "baidu.com";
		
		WangXinFlowDeal lffd = new WangXinFlowDeal();
		String sign = lffd.paramSign(userName, mobile, orderMeal, timeStamp, key);
		System.out.println("sign = [" + sign + "]");
		String paramData = lffd.paramFormat(userName, mobile, orderMeal, orderTime, msgId, range, sign, timeStamp, notifyUrl);
		
		System.out.println("请求内容[" + paramData + "]");
		
		try {
			String result = ToolHttp.post(false, linkUrl, paramData, null);
			System.out.println(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private static void queryOrder() {
		String queryOrderUrl = "http://103.254.78.187:8083/gatewayFlow/order/inquire";
		String key = "54F896BF-3399-4BC7-BF2A-EF72F4107F13";
		String userName = "JNhaobaiBDP";
		
		String msgId = "hb"+DateUtils.getNowTimeToMS()+"13280009366"+GenerateData.getStrData(2);
		
		WangXinFlowDeal lffd = new WangXinFlowDeal();
		
		String sign = lffd.SHA1("userName" + userName + "msgId" + msgId + "key" + key);
		System.out.println("sign = [" + sign + "]");
		
		Map<String, String> paramMap = new LinkedHashMap<String, String>();
		paramMap.put("userName", userName);
		paramMap.put("msgId", msgId);
		paramMap.put("sign", sign);
		
		String paramData = JSONObject.toJSONString(paramMap);
		
		System.out.println("请求内容[" + paramData + "]");
		
		try {
			String result = ToolHttp.post(false, queryOrderUrl, paramData, null);
			System.out.println(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
